﻿import plugin from '../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import request from 'request'
import { segment } from 'oicq'
import fs from 'node:fs'
import download from 'download'
import yaml from "yaml"
import convert from 'xml-js'

//获取网页截图
import { createRequire } from 'module'
import { match } from 'node:assert'
const require = createRequire(import.meta.url)

// 创建文件夹
let fl = `${process.cwd()}/data/xianyu`;
if (!fs.existsSync(fl)) {
    fs.mkdirSync(fl);
}
if (!fs.existsSync(`${fl}/scuserck.yaml`)) {
    let notes = {
        "用户qq": "ck"
    }
    let yamlstr = yaml.stringify(notes);//json转yaml
    fs.writeFile(`${fl}/scuserck.yaml`, yamlstr, function (err) {
        if (err) throw err;
    })
}
if (!fs.existsSync(`${fl}/caizhi.yaml`)) {
    let notes = [{
        "user": "用户qq",
        "urls": "链接",
    }]
    let yamlstr = yaml.stringify(notes);//json转yaml
    fs.writeFile(`${fl}/caizhi.yaml`, yamlstr, function (err) {
        if (err) throw err;
    })
}
if (!fs.existsSync(`${fl}/sc.yaml`)) {
    fs.writeFile(`${fl}/sc.yaml`, '[]', (err) => {
        if (err) throw err;
    });
}
if (!fs.existsSync(`${fl}/caizhi.yaml`)) {
    let notes = [{
        "user": "用户qq",
        "urls": "链接",
    }]
    let yamlstr = yaml.stringify(notes);//json转yaml
    fs.writeFile(`${fl}/caizhi.yaml`, yamlstr, function (err) {
        if (err) throw err;
    })
}
if (!fs.existsSync(`${fl}/mods`)) {
    fs.mkdirSync(`${fl}/mods`);
}
const tz = { "综合": 16, "作品": 6, "发布": 6, "公告": 14, "教程": 12, "联机": 3, "mod": 2, "MOD": 2, "mod讨论": 2, };
const t = { "材质": "方块材质", "皮肤": "人物皮肤", "存档": "世界", "家具": "家具包" };

export class calc extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '生存战争插件',
            /** 功能描述 */
            dsc: 'scmod',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 11451,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '^#sc搜(mod|模组|MOD)(.*)$',
                    /** 执行方法 */
                    fnc: 'schubmod',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^在$',
                    /** 执行方法 */
                    fnc: 'calc'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^选mod',
                    /** 执行方法 */
                    fnc: 'scmod'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^选(材质|皮肤|存档|家具)',
                    /** 执行方法 */
                    fnc: 'schub'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^搜(材质|皮肤|存档|家具)',
                    /** 执行方法 */
                    fnc: 'sousuo'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc我的mod列表',
                    /** 执行方法 */
                    fnc: 'usermod'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc修改(社区)?昵称',
                    /** 执行方法 */
                    fnc: 'usernickname'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc绑定ck',
                    /** 执行方法 */
                    fnc: 'binding'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc登录',
                    /** 执行方法 */
                    fnc: 'sclogin'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc注册([\s\S]*)',
                    /** 执行方法 */
                    fnc: 'screg'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc我的(社区)?信息',
                    /** 执行方法 */
                    fnc: 'userindex'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc(社区)?赞助(列表)?',
                    /** 执行方法 */
                    fnc: 'zanzu'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc发帖[\s\S]*',
                    /** 执行方法 */
                    fnc: 'fatie'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc(综合|作品|发布|教程|联机|mod讨论|mod|MOD)(贴|区)',
                    /** 执行方法 */
                    fnc: 'cate16'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?(sc)?查看',
                    /** 执行方法 */
                    fnc: 'chakan'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc搜索?(用户|大佬|玩家|人)',
                    /** 执行方法 */
                    fnc: 'searchuser'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#?sc搜索?(综合|作品|发布|教程|联机|mod讨论|mod|MOD)(贴|区)',
                    /** 执行方法 */
                    fnc: 'searchbbs'
                },
            ]
        })
    }

    /**
     * 搜帖子
     */

    async searchbbs(e) {
        let type = e.msg.match(/#?sc搜索?(综合|作品|发布|教程|联机|mod讨论|mod|MOD)(贴|区).*/)[1];
        let emsg = e.msg.replace(/#?sc搜索?(综合|作品|发布|教程|联机|mod讨论|mod|MOD)(贴|区)?/, '');
        let typeid = tz[type];
        let response = await fetch(`https://m.schub.top/com/api/cate/searchbbs?cid=${typeid}&key=${emsg}`);
        let obj = await response.json();
        if (!obj.data) {
            e.reply('什么有也没搜到')
            return true;
        }
        let data_msg = [];
        for (let i in obj.data) {
            let time = new Date(+obj.data[i].addTime * 1000);
            let formattedTime = time.getFullYear() + '-' + (time.getMonth() + 1) + '-' + time.getDate() + ' ' + time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
            let msg = {
                message: [
                    `标题：${obj.data[i].title}`,
                    `\n发布时间：${formattedTime}`,
                    `\n浏览：${obj.data[i].views}`,
                    `\n回复：${obj.data[i].replies}`,
                    `\n帖子主页：https://m.schub.top/com/bbs/${obj.data[i].id}`,
                ],
                nickname: Bot.nickname,
                user_id: Bot.uin
            }
            data_msg.push(msg);
        }

        //制作合并转发
        let ForwardMsg;
        if (this.e.isGroup) {
            ForwardMsg = await e.group.makeForwardMsg(data_msg);
        } else {
            ForwardMsg = await e.friend.makeForwardMsg(data_msg);
        }
        e.reply(ForwardMsg)
        return true;
    }

    /**
     * 搜用户
     */
    async searchuser(e) {
        let emsg = e.msg.replace(/#?sc搜索?(用户|大佬|玩家|人)/, '');
        let response = await fetch(`https://m.schub.top/com/api/user/searchuser?nickname=${emsg}`);
        let obj = await response.json();

        if (!obj.data) {
            e.reply('什么有也没搜到')
            return true;
        }
        let data_msg = [];
        for (let i in obj.data) {
            let isadmin;
            let time = new Date(+obj.data[i].last_login_time * 1000);
            let formattedTime = time.getFullYear() + '-' + (time.getMonth() + 1) + '-' + time.getDate() + ' ' + time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
            if (obj.data[i].isadmin == '1') {
                isadmin = '\n管理员：是';
            } else {
                isadmin = ' ';
            }
            let msg = {
                message: [
                    `昵称：${obj.data[i].nickname}`,
                    `\n用户主页：https://m.schub.top/com/user/${obj.data[i].id}`,
                    `\n最后登录时间：${formattedTime}`,
                    `\n经验值：${obj.data[i].money}`,
                    isadmin
                ],
                nickname: Bot.nickname,
                user_id: Bot.uin
            }
            data_msg.push(msg);
        }

        //制作合并转发
        let ForwardMsg;
        if (this.e.isGroup) {
            ForwardMsg = await e.group.makeForwardMsg(data_msg);
        } else {
            ForwardMsg = await e.friend.makeForwardMsg(data_msg);
        }
        e.reply(ForwardMsg)
        return true;
    }

    /**
     * 发送帖子
     */

    async fatie(e) {
        try {
            var emsg = e.msg.match(/#?sc发帖(综合|作品|发布|教程|联机|mod讨论|mod|MOD|帮助)(贴|区)?([\s\S]*)/)[1];
            if (emsg == '帮助') {
                e.reply(`#sc发帖<板块> #标题：你的标题 #内容：发帖内容\n板块可选“(综合|作品/发布|教程|联机|mod讨论)区”示例：\n#sc发帖作品区#标题：这是我的标题#内容：这是机器人帮我发送的帖子内容`)
                return true;
            }
            var biaoti = e.msg.match(/#标题(：|:)([\s\S]*)#内容(：|:)/)[2];
            var neiron = e.msg.match(/#标题[\s\S]*#内容(：|:)([\s\S]*)/)[2];
        } catch {
            console.log('没有内容');
            e.reply(`发帖格式错误，可发送#sc发帖帮助 查看格式`);
            return true;
        }
        if (biaoti == '这是我的标题' || neiron == '这是机器人帮我发送的帖子内容') {
            e.reply('格式对了，但你为什么要复制示例内容！哼哼哼啊啊啊啊啊！！')
            return true;
        }
        if (emsg == '公告') {
            e.reply('别在公告区发帖，已阻止')
            return true;
        }
        let cid = tz[type];
        console.log('---标题：' + biaoti + '\n---内容：' + neiron + '\n---板块id：' + cid);

        let File = `${fl}/scuserck.yaml`;
        let userid = e.user_id;

        // 判断文件夹是否存在
        if (!fs.existsSync(`${fl}`)) {
            // 创建文件夹
            fs.mkdirSync(`${fl}`);
        }
        if (!fs.existsSync(File)) {
            e.reply('你还没有登录或绑定ck');
            return true;
        } else {
            //打开文件
            let yam = fs.readFileSync(`${fl}/scuserck.yaml`, 'utf8');
            var obj = yaml.parse(yam); //yaml转json
        }

        if (!obj[userid]) {
            e.reply('你还没有登录或绑定ck');
            return true;
        }

        //处理内容
        neiron = neiron.replace(/ /g, "&nbsp");
        neiron = neiron.match(/.*/g);
        let content;
        for (let i in neiron) {
            if (i % 2 === 0) {
                content = `${content}<p>${neiron[i]}</p>`;
            }
        }
        let Cookie = obj[userid][0];
        let url = 'http://m.schub.top/com/api/bbs/publish';

        fetch(url, {
            method: 'POST',
            headers: {
                'Cookie': Cookie,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `cid=${cid}&content=${encodeURI(content)}&title=${encodeURI(biaoti)}`
        })
            .then(res => res.json())
            .then(json => {
                console.log(json)
                e.reply(json.msg);
                return true;
            })
            .catch(err => console.log(err));

    }

    /**
     * 查看帖子详情
     */

    async chakan(e) {
        let user = e.user_id;
        let File = `${fl}/scbbs.yaml`;
        if (!fs.existsSync(File)) {
            e.reply('请先使用“#sc综合区”')//发送消息
            return true;
        }
        let yam = fs.readFileSync(File, 'utf8');
        let obj = yaml.parse(yam); //yaml转json

        let emsg = e.msg.replace(/#?(sc)?查看/, '');
        let regex = /\d+/g;
        if (!regex.test(emsg[0])) {
            e.reply(`请使用数字0-9`)
            return true;
        }
        if (!obj[user][emsg]) {
            e.reply('没有这个序号')
            return true;
        }
        //获取网页截图
        const puppeteer = require('puppeteer');
        const browser = await puppeteer.launch({
            headless: true,
            args: [
                '--disable-gpu',
                '--disable-dev-shm-usage',
                '--disable-setuid-sandbox',
                '--no-first-run',
                '--no-sandbox',
                '--no-zygote',
                '--single-process'
            ]
        });
        const page = await browser.newPage();
        await page.goto(`https://m.schub.top/com/bbs/${obj[user][+emsg - 1]}`);
        await page.setViewport({
            width: 1920,
            height: 1080
        });
        await this.reply(segment.image(await page.screenshot({
            fullPage: true
        })))
        await browser.close();
    }

    /**
     * 社区帖子
     */

    async cate16(e) {
        let userid = e.user_id;
        let emsg = e.msg.replace(/#?sc(.{2,})(贴|区)/, '');
        let type = e.msg.match(/#?sc(.{2,})(贴|区).*/)[1];

        let typeid = tz[type];
        if (!emsg) {
            var pg = 1;
        } else {
            var pg = emsg;
        }
        console.log(pg);

        let response = await fetch(`https://m.schub.top/com/cate/${typeid}?page=${pg}`); //调用接口获取数据
        let obj = await response.text();

        let title = obj.match(/.*<span class="topic-title">.*/g); //帖子标题和链接
        let browse = obj.match(/class="human-readable-number"\stitle="\d+"/g); //偶数为回复，奇数为浏览
        let up = obj.match(/<strong>.*<\/strong>/g); //发帖人昵称
        let time = obj.match(/>\d{4}年\d{2}月\d{2}日\s.*\s\d{2}:\d{2}</g); //发帖时间
        let page = obj.match(/>\d+ \/ \d+</);

        let data_msg = [
            {
                message: `-->社区${type}区<--`,
                nickname: Bot.nickname,
                user_id: Bot.uin
            },
            {
                message: `当前页：${page}\n发送“#查看+序号”查看帖子详情\n发送“#sc${type}区+数字”跳转指定页`,
                nickname: Bot.nickname,
                user_id: Bot.uin
            }
        ]; //存储发言消息
        let titleid = []; //帖子id

        //分练回复和浏览
        let browse1 = []; //回复
        let browse2 = []; //浏览
        let newtime = []; //时间
        for (let i in browse) {
            if (i % 2 === 0) {
                browse1.push(browse[i]);
            } else {
                browse2.push(browse[i]);
            }
        }
        for (let i in browse) {
            if (i % 2 === 0) {
                newtime.push(time[i]);
            }
        }

        //添加内容
        for (let i in title) {
            let title1 = title[i].match(/<span class="topic-title">(.*)<\/span><\/a>/)[1]; //标题
            let url = title[i].match(/\/com\/bbs\/\d+/); //链接 /com/bbs/XXX
            let hf = browse1[i].match(/title="(\d+)"/)[1]; //回复数
            let br = browse2[i].match(/title="(\d+)"/)[1]; //浏览数
            let name = up[i].match(/<strong>(.*)<\/strong>/)[1]; //名字
            let id = url[0].match(/(\d+)/)[1];

            titleid.push(id);
            data_msg.push({
                message: [
                    `${+i + 1}、${title1}\n`,
                    `浏览数：${br}； 回复数：${hf}\n`,
                    `发帖人：${name}\n`,
                    `${newtime[i]}\n`,
                    `https://m.schub.top${url[0]}`,
                ],
                nickname: Bot.nickname,
                user_id: Bot.uin
            })
        }
        let File = `${fl}/scbbs.yaml`;
        if (!fs.existsSync(File)) {
            let notes = {
                "用户qq": "帖子id"
            }
            notes[userid] = titleid;
            let yamlstr = yaml.stringify(notes);//json转yaml
            fs.writeFile(File, yamlstr, function (err) {
                if (err) throw err;
            })
        } else {
            //打开文件
            let yam = fs.readFileSync(File, 'utf8');
            let obj = yaml.parse(yam); //yaml转json
            obj[userid] = titleid;
            let yamlstr = yaml.stringify(obj);//json转yaml
            fs.writeFile(File, yamlstr, function (err) {
                if (err) throw err;
            });
        }

        //制作合并转发
        let ForwardMsg;
        if (this.e.isGroup) {
            ForwardMsg = await e.group.makeForwardMsg(data_msg);
        } else {
            ForwardMsg = await e.friend.makeForwardMsg(data_msg);
        }
        e.reply(ForwardMsg)//发送消息
        return true;
    }

    /**
     * 赞助列表
     */

    async zanzu(e) {
        let response = await fetch(`https://m.schub.top/com/sponsor`); //调用接口获取数据
        let obj = await response.text();
        let name = obj.match(/<table id="ts" valign="top" class="table">(.*)<\/table>/)[1];
        name = name.replace(/<tr><th>/g, '');
        name = name.replace(/<\/th><\/tr>/g, '');
        name = name.replace(/\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\]/g, '');
        name = name.replace(/<\/font><\/th><th>/g, '');
        name = name.replace(/<\/th><th>/g, '');
        name = name.replace(/<font color="blue">/g, '\n');
        name = name.replace(/<font color="red">/g, '');
        name = name.replace(/<\/font>/g, '');
        name = name.match(/.*/g);
        console.log(name)

        let data_name = ['赞助列表如下：'];

        for (let i = 1; i < name.length; i++) {
            if (name[i]) {
                data_name.push(`\n${name[i]}`)
            }
        }

        let data_msg = {
            message: data_name,
            nickname: Bot.nickname,
            user_id: Bot.uin
        }

        //制作合并转发
        let ForwardMsg;
        if (this.e.isGroup) {
            ForwardMsg = await e.group.makeForwardMsg(data_msg);
        } else {
            ForwardMsg = await e.friend.makeForwardMsg(data_msg);
        }
        e.reply(ForwardMsg)//发送消息
        return true;
    }

    /**
     * 注册账号
     */

    async screg(e) {
        let emsg = e.msg.match(/.*/g);
        let user = emsg[2];
        let pass = emsg[4];
        let email = emsg[6];
        let nickname = emsg[8];
        console.log(emsg)
        if (!user || !pass || !email || !nickname) {
            e.reply('注册格式不正确,请使用以下格式\n#sc注册\n<账号>\n<密码>\n<邮箱>\n<昵称>');
            return true;
        }

        //注册
        let response = await fetch(`https://m.schub.top/com/api/user/reg?user=${user}&pass=${pass}&repass=${pass}&email=${email}&nickname=${nickname}`); //调用接口获取数据
        let obj = await response.json();
        e.reply(obj.msg);
        return true;
    }

    /**
     * 登录社区
     */

    async sclogin(e) {
        if (!e.msg.match(/#?sc登录 ?(社区)? ?(\w+) /) || !e.msg.match(/ (.*)/)) {
            e.reply('请在后面加上账号和密码\n格式为“#sc登录<账号>空格<密码>”');
            return true;
        }
        let user = e.msg.match(/#?sc登录 ?(社区)? ?(\w+) /)[2];
        let pass = e.msg.match(/ (.*)/)[1];
        console.log(user + '//' + pass)
        let userid = e.user_id;
        // 判断文件夹是否存在
        if (!fs.existsSync(`${fl}`)) {
            // 创建文件夹
            fs.mkdirSync(`${fl}`);
        }
        let File = `${fl}/scuserck.yaml`;

        let url = `https://m.schub.top/com/api/user/login?user=${user}&pass=${pass}`;

        request(url, (err, res, body) => {
            if (err) {
                console.log(err);
            } else {
                let obj = JSON.parse(body);
                let emsg = obj.msg;
                //登录失败返回接口提示
                if (emsg != '登录成功') {
                    e.reply(emsg);
                    return true;
                }
                let PHPSESSID = res.headers['set-cookie'][0].split(';')[0].split('=')[1];
                let tk = res.headers['set-cookie'][1].split(';')[0].split('=')[1];
                console.log(tk);
                console.log(PHPSESSID);
                if (tk) {
                    //登录成功，保存ck
                    let ck = `userid=${tk};PHPSESSID=${PHPSESSID}`
                    if (!fs.existsSync(File)) {
                        let notes = {
                            "用户qq": "ck"
                        }
                        notes[userid] = [ck];
                        let yamlstr = yaml.stringify(notes);//json转yaml
                        fs.writeFile(File, yamlstr, function (err) {
                            if (err) throw err;
                        })
                        e.reply(emsg);
                        return true;
                    } else {
                        //打开文件
                        let yam = fs.readFileSync(File, 'utf8');
                        let obj = yaml.parse(yam); //yaml转json
                        obj[userid] = [ck];
                        let yamlstr = yaml.stringify(obj);//json转yaml
                        fs.writeFile(File, yamlstr, function (err) {
                            if (err) throw err;
                        });
                        e.reply(emsg);
                        return true;
                    }
                }
            }
        });
    }

    /**
     * 绑定社区ck
     */

    async binding(e) {
        let userid = e.user_id;
        let ck = e.msg.match(/userid=[a-z0-9]*; ?PHPSESSID=[a-z0-9]*/);
        if (!ck) {
            e.reply('请与ck一同发送，ck格式为userid=XXX; PHPSESSID=XXX');
            return true;
        }
        let File = `${fl}/scuserck.yaml`;

        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        let obj = yaml.parse(yam); //yaml转json
        obj[userid] = ck;
        let yamlstr = yaml.stringify(obj);//json转yaml
        fs.writeFile(File, yamlstr, function (err) {
            if (err) throw err;
            e.reply('绑定成功');
            return true;
        });
    }

    /***
     * 查看自己的信息
     */

    async userindex(e) {
        let File = `${fl}/scuserck.yaml`;
        let userid = e.user_id;
        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        var obj = yaml.parse(yam); //yaml转json

        if (!obj[userid]) {
            e.reply('你还没有登录或绑定ck');
            return true;
        }

        let Cookie = obj[userid][0];
        fetch('https://m.schub.top/com/user/index', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Cookie': Cookie,
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(res => res.text()).then(body => {
            // fs.writeFile(`${fl}/AAAAA.html`,body,function (err){
            //     if (err) throw err;
            // });
            // console.log(body)
            let username = body.match(/title="(.*?)">.*<\/div>/);
            username = username[username.length - 2].match(/title="(\S+)">.*<\/div>/)[1];
            let message = body.match(/.*(消息.*)<\/a>/)[1];
            let Lastlogin = body.match(/.*(上次登陆.*)<\/p>/)[1];
            let exp = body.match(/.*(经验.*)<\/p>/)[1];
            let email = body.match(/.*(邮箱.*)<\/p>/)[1];

            e.reply([
                segment.at(userid),
                `\n社区昵称：${username}`,
                `\n${message}`,
                `\n${Lastlogin}`,
                `\n${exp}`,
                `\n${email}`,
            ]);
            return true;
        })

    }

    /**
     * 修改社区昵称
     */

    async usernickname(e) {
        let File = `${fl}/scuserck.yaml`;
        let userid = e.user_id;
        let name = e.msg.match(/#?sc修改(社区)?昵称(.*)/)[2];
        console.log(name)
        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        var obj = yaml.parse(yam); //yaml转json

        if (!obj[userid]) {
            e.reply('你还没有登录或绑定ck');
            return true;
        }

        let Cookie = obj[userid][0];
        fetch('https://m.schub.top/com/user/index?do=changenickname&ext=submit', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Cookie': Cookie,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `nickname=${name}`
        }).then(res => {
            if (res) {
                e.reply('社区昵称修改成功', true);
                return true;
            }
        })
    }

    /** 
     * 查看发布的mod
     */

    async usermod(e) {
        let File = `${fl}/scuserck.yaml`;
        let data_msg = [];//存储消息
        let userid = e.user_id;

        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        let obj = yaml.parse(yam); //yaml转json

        if (!obj[userid]) {
            e.reply('你还没有登录或绑定ck');
            return true;
        }

        let Cookie = obj[userid][0];
        fetch('https://m.schub.top/com/mods/list', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Cookie': Cookie,
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(res => res.text()).then(body => {
            // fs.writeFile(File,body,function (err){
            //     if (err) throw err;
            // });
            let username = body.match(/alt="(.*?)"/)[1];
            data_msg.push('用户名：' + username + '\n你发布的mod如下：');

            let list = body.match(/.*target="_blank".*/g)
            for (let i = 0; i < list.length - 1; i++) {
                let st = list[i].match(/.*<a.*target="_blank">(.*?)<\/a>/)[1];
                data_msg.push(`\n${i + 1}、${st}`);
            }
            e.reply(data_msg);
            return true;
        });
    }

    /***
     * 搜索社区内容
     * 
     */

    async sousuo(e) {
        let emsg = e.msg.replace(/搜(材质|皮肤|存档|家具)/g, '');
        let list = e.msg.match(/材质|皮肤|存档|家具/);
        let type = t[list[0]];

        let url = `https://m.schub.top/com/list?Type=${type}&key=${emsg}`;
        let response = await fetch(encodeURI(url)); //调用接口获取数据
        let res = await response.text();
        let ds = convert.xml2json(res);//xml转json
        // console.log(ds);
        ds = JSON.parse(ds);

        if (!ds.elements[0].elements) {
            e.reply('什么都没有搜到');
            return true;
        }
        console.log('结果长度' + ds.elements[0].elements.length);

        //获取配置文件
        let File = `${fl}/caizhi.yaml`;

        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        var obj = yaml.parse(yam); //yaml转json

        // 查找用户，没有则创建
        let user;
        for (const i in obj) {
            if (obj[i].user == e.user_id) {
                user = i;
            }
        }
        if (!user) {
            obj.push({
                "user": e.user_id,
                "urls": []
            })
            user = obj.length - 1;
        }

        //写入消息
        let data_msg = []; //存储消息
        let urls = []; //存储链接
        for (const i in ds.elements[0].elements) {
            data_msg.push(
                {
                    message: [
                        `${[+i + 1]}、名称：${ds.elements[0].elements[i].attributes.Name}\n`,
                        `类型：${ds.elements[0].elements[i].attributes.Type}\n`,
                        `评分：${ds.elements[0].elements[i].attributes.RatingsAverage}\n`,
                        `${ds.elements[0].elements[i].attributes.ExtraText}`,
                    ],
                    nickname: Bot.nickname,
                    user_id: Bot.uin
                }
            )
            urls.push({
                "url": `${ds.elements[0].elements[i].attributes.Url}`,
                "name": `${ds.elements[0].elements[i].attributes.Name}`
            });
        }
        data_msg.push(
            {
                message: `发送“选${list[0]}1”获取文件`,
                nickname: Bot.nickname,
                user_id: Bot.uin
            }
        )

        //写入文件
        obj[user].urls = urls;
        let yamlstr = yaml.stringify(obj);//json转yaml
        fs.writeFile(File, yamlstr, function (err) {
            if (err) throw err;
        });

        //制作合并转发
        let ForwardMsg;
        if (this.e.isGroup) {
            ForwardMsg = await e.group.makeForwardMsg(data_msg);
        } else {
            ForwardMsg = await e.friend.makeForwardMsg(data_msg);
        }
        e.reply(ForwardMsg)//发送消息
        return true;
    }

    async calc(e) {
        await this.e.reply(`在在在`);//发送消息
        return true; //返回true 阻挡消息不再往下
    }

    async schubmod(e) {
        let emsg = e.msg.replace(/(搜mod|搜模组|搜MOD)/g, '');

        let url = `https://m.schub.top/com/mods/viewlist?q=${emsg}`;
        let response = await fetch(url); //调用接口获取数据
        let res = await response.text();

        let div = /<div style="display:inline-block;">[\s\S]*<\/div>/g // 获取所有搜索结果
        let a = /<a.*<\/a>/g; //提取名字与链接
        let name = /&nbsp.*&nbsp/g; //提取模组名字
        let span = /<span style="font-size: 0.6em;font-family: cursive;">.*<\/span><\/div>/g; //获取下载以及更新信息

        let textSC = res.match(div);//提取到的所有结果
        let online = textSC[0].match(/当前在线.*人/g); //在线人数

        //获取配置文件
        let File = `${fl}/sc.yaml`;
        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        var obj = yaml.parse(yam); //yaml转json

        let data_name = [];//存储名字，发布时间等内容
        let urls = [];//存储链接

        if (textSC) {
            let nm = textSC[0].match(a); //名字
            let num = textSC[0].match(span); //发布时间，下载次数

            // 查找用户，没有则创建
            let user;
            for (const i in obj) {
                if (obj[i].user == e.user_id) {
                    user = i;
                }
            }
            if (!user) {
                obj.push({
                    "user": e.user_id,
                    "urls": []
                })
                user = obj.length - 1;
            }
            // 前缀
            data_name.push({
                message: `发送“选mod+序号”可以获取最新文件`,
                nickname: Bot.nickname,
                user_id: Bot.uin
            });
            for (let key = 0; key < nm.length - 2; key++) {
                //取出名字
                let modname = nm[key].match(name);
                modname = modname[0].replace(/&nbsp;/g, '');
                modname = modname.replace(/<font color="red">/g, '');
                modname = modname.replace(/<\/font>/g, '');
                modname = modname.replace(/&nbsp/g, '');
                console.log(modname);
                //取出链接
                let modurl = nm[key].match(/\/com\/mods\/preview\/\d+/g);
                console.log('https://m.schub.top' + modurl[0]);
                //取出下载次数与更新时间
                let modnum = num[key].replace(/<span style="font-size: 0.6em;font-family: cursive;">/, '');
                modnum = modnum.replace(/<font color="red">/g, '');
                modnum = modnum.replace(/<\/font>/g, '');
                modnum = modnum.replace(/&emsp;/g, ';');
                modnum = modnum.replace(/<font color="green">/g, '');
                modnum = modnum.replace(/<\/span><\/div>/g, '');
                console.log(modnum + '\n-------------');
                //写入消息
                data_name.push(
                    {
                        message: `${[key + 1]}、${modname}\n${modnum}\nhttps://m.schub.top${modurl[0]}`,
                        nickname: Bot.nickname,
                        user_id: Bot.uin
                    }
                );
                //写入链接
                urls.push('https://m.schub.top' + modurl[0]);
            }
            //写入文件
            obj[user].urls = urls;
            let yamlstr = yaml.stringify(obj);//json转yaml
            fs.writeFileSync(`${fl}/sc.yaml`, yamlstr, 'utf8');

            //制作合并转发
            let ForwardMsg;
            if (this.e.isGroup) {
                ForwardMsg = await e.group.makeForwardMsg(data_name);
            } else {
                ForwardMsg = await e.friend.makeForwardMsg(data_name);
            }
            e.reply(ForwardMsg)//发送消息
            return true;
        }
        e.reply(`什么也没搜到`)
        return true;
    }

    /**
     * 使用group.fs方法上传群文件
     */

    async scmod(e) {
        let emsg = e.msg.replace(/选mod ?/g, '');
        let regex = /\d+/g;
        if (!regex.test(emsg[0])) {
            e.reply(`请使用数字0-9`)
            return true;
        }
        emsg = +emsg - 1;

        //获取配置文件
        let File = `${fl}/sc.yaml`;
        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        var obj = yaml.parse(yam);//yaml转json
        let user;
        for (const i in obj) {
            if (obj[i].user == e.user_id) {
                user = i;
            }
        }

        if (!user) {
            e.reply(`请先使用"搜mod"指令`)
            return true;
        }

        if (!obj[user].urls[emsg]) {
            e.reply('没有这个序号')
            return true;
        }

        let url = /\/com\/down?.*(?=" rel)/g; //取出下载链接
        let name = /<span class="px-1 text-bold">.*/g; //取出文件名字

        let response = await fetch(`${obj[user].urls[emsg]}`); //调用接口获取数据
        console.log(obj[user].urls[emsg]);
        let res = await response.text();

        if (res) {
            //提取链接
            let scmod = res.match(url);
            scmod = `https://m.schub.top${scmod[0]}`;
            console.log(scmod);

            //提取文件名
            let version = res.match(name);
            version = version[0].replace(/<span class="px-1 text-bold">/g, '');
            version = version.replace(/<\/span>.*/g, '');

            //提取后缀
            let suf = res.match(name);
            suf = suf[0].match(/(scmod|zip|apk)/g);

            // 创建文件夹
            const dirPath = `${fl}/mods`;
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath);
            }

            //下载路径
            let file = `${fl}/mods/${version}.${suf[0]}`;
            console.log(file);

            e.reply('下载时间会有点长，请耐心等待')
            //下载文件
            request(scmod, (err, response, body) => {
                if (err) { e.reply('请求出错了，悲') }
                let urlname = encodeURI(response.request.uri.href);
                let head = urlname.match(/https:\/\/cdn.schub.top\/modsfile\/\d{4}\/\d{2}\/\d{2}\//g);
                let options = `${head}${version}.${suf}`;
                console.log(options);
                (async () => {
                    await download(encodeURI(options), `${fl}/mods/`, {
                        filename: `${version}.${suf[0]}`,
                    });
                    e.reply([
                        segment.at(e.user_id),
                        ` 下载成功了`
                    ])
                    e.group.fs.upload(file, '/', `${version}.${suf}`);
                })();

                // // 发送链接
                // let data = download(encodeURI(options));
                // fs.promises.writeFile(file,data);
                // e.reply(encodeURI(options))
                // e.reply('复制链接，打开游戏在：内容-链接 处填写链接，类型选择模组，然后点击下载，按照提示安装即可')
                // return true;
            });
        }
    }

    /**
     * 搜索其他资源
     */
    async schub(e) {
        let emsg = e.msg.replace(/选(材质|皮肤|存档|家具) ?/g, '');
        let regex = /\d+/g;
        if (!regex.test(emsg[0])) {
            e.reply(`请使用数字0-9`)
            return true;
        }
        emsg = +emsg - 1;
        let list = e.msg.match(/材质|皮肤|存档|家具/);
        let type = t[list[0]];

        //获取配置文件
        let File = `${fl}/caizhi.yaml`;
        //打开文件
        let yam = fs.readFileSync(File, 'utf8');
        var obj = yaml.parse(yam);//yaml转json

        let user;
        for (const i in obj) {
            if (obj[i].user == e.user_id) {
                user = i;
            }
        }

        if (!user) {
            e.reply(`请先使用"搜${list[0]}"指令`)
            return true;
        }

        if (!obj[user].urls[emsg]) {
            e.reply('没有这个序号')
            return true;
        }

        request(obj[user].urls[emsg].url, (err, response, body) => {
            if (err) {
                e.reply('请求出错了，悲')
                return true;
            }
            e.reply('下载时间会有点长，请耐心等待')
            let url = response.request.uri.href.match(/https:\/\/cdn.schub.top\/gamefiles\/.*\//);
            let schub = encodeURI(`${url[0]}${obj[user].urls[emsg].name}.${type}`);
            console.log(`${url[0]}${obj[user].urls[emsg].name}.${type}`);
            (async () => {
                await download(schub, `${fl}/mods`, {
                    filename: `${obj[user].urls[emsg].name}.${type}`,
                });
                e.reply([
                    segment.at(e.user_id),
                    ` 下载成功了`
                ])
                //下载路径
                let file = `${fl}/mods/${obj[user].urls[emsg].name}.${type}`;
                e.group.fs.upload(file, '/', `${obj[user].urls[emsg].name}.${type}`);
            })();
        });
    }

}